while loop in C

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.

Syntax of while loop in C language

The syntax of while loop in c language is given below:
    
        while(condition){  
            //code to be executed  
            }    
    
            

Example of the while loop in C language

Let's see the simple program of while loop that prints table of 1.
    
        #include  
            int main(){    
            int i=1;      
            while(i<=10){      
            printf("%d n",i);      
            i++;      
            }  
            return 0;  
            }    
    
            

Output

1 2 3 4 5 6 7 8 9 10

Program to print table for the given number using while loop in C


    #include  
        int main(){    
        int i=1,number=0,b=9;    
        printf("Enter a number: ");    
        scanf("%d",&number);    
        while(i<=10){    
        printf("%d n",(number*i));    
        i++;    
        }    
        return 0;  
        }   

        

Output

Enter a number: 50 50 100 150 200 250 300 350 400 450 500 Enter a number: 100 100 200 300 400 500 600 700 800 900 1000

Properties of while loop

Example 1:

    
        #include  
            void main ()  
            {  
                int j = 1;  
                while(j+=2,j<=10)  
                {  
                    printf("%d ",j);   
                }  
                printf("%d",j);  
            }  
    
            

Output

3 5 7 9 11

Example 2:

        
            #include  
                void main ()  
                {  
                    while()  
                    {  
                        printf("hello Javatpoint");   
                    }  
                }    
        
                

Output

compile time error: while loop can't be empty

Example 3:

            
                #include  
                    void main ()  
                    {  
                        int x = 10, y = 2;  
                        while(x+y-1)  
                        {  
                            printf("%d %d",x--,y--);  
                        }  
                    }  
            
                    

Output

infinite loop

Infinitive while loop in C

If the expression passed in while loop results in any non-zero value then the loop will run the infinite number of times.
            
                while(1){  
                    //statement  
                    }